package com.hc.likelistenmusic.presenter

import android.graphics.BitmapFactory
import android.media.MediaMetadataRetriever
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.util.Log
import com.hc.likelistenmusic.activity.LocalMusicActivity
import com.hc.likelistenmusic.bean.LocalMusic
import com.hc.likelistenmusic.model.LocalMusicModel
import com.shuyu.gsyvideoplayer.GSYVideoManager
import com.shuyu.gsyvideoplayer.listener.VideoAllCallBack
import com.shuyu.gsyvideoplayer.player.PlayerFactory
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer
import com.shuyu.gsyvideoplayer.video.base.GSYVideoView
import com.shuyu.gsyvideoplayer.video.base.GSYVideoView.CURRENT_STATE_PLAYING
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import tv.danmaku.ijk.media.exo2.Exo2PlayerManager

class LocalMusicPresenter(var mLocalMusicActivity: LocalMusicActivity)  : VideoAllCallBack{
    val TAG = "HUACHEN_LocalMusicPresenter"
    var mLocalMusicModel: LocalMusicModel
    val TYPE_UPDATE_PROGRESS = 1
    var mCurrentLocalMusicPath: String? = null
    lateinit var mSvp: StandardGSYVideoPlayer
    var mHandler: Handler = object : Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            if (msg.what == TYPE_UPDATE_PROGRESS) {
                mLocalMusicActivity.onProgress(mSvp.currentPositionWhenPlaying.toInt(),
                    mSvp.duration.toInt()
                )
                sendProgress()
            }
        }
    }
    var mMmr: MediaMetadataRetriever

    init {
        mLocalMusicModel = LocalMusicModel(mLocalMusicActivity.applicationContext)
        mMmr = MediaMetadataRetriever()
    }

    fun sendProgress() {
        var m = Message.obtain()
        m.what = TYPE_UPDATE_PROGRESS
        mHandler.sendMessageDelayed(m, 1000)
    }

    fun cancelProgress() {
        mHandler.removeMessages(TYPE_UPDATE_PROGRESS)
    }

    fun prepareMusicAsync(lm: LocalMusic) {
        try {
            cancelProgress()
            mLocalMusicActivity.resetUI()
            mCurrentLocalMusicPath = "${lm.path}"
            mSvp.onVideoReset()
            mSvp.setUp(lm.path,false,"")
            mSvp.startPlayLogic()
        } catch (e: Exception) {
            CoroutineScope(Dispatchers.Main).launch {
                mLocalMusicActivity.onError()
                mLocalMusicActivity.showToast(mLocalMusicModel.getPrepareErrorString())
            }
            e.printStackTrace()
            Log.d(TAG, "缓冲失败1")
        }
    }

    fun getNoMusicFromLrcInfo(): String {
        return mLocalMusicModel.getNoMusicFromLrcString()
    }

    fun getNoMusicFromMusicInfo(permission: Boolean): String {
        return mLocalMusicModel.getNoMusicFromMusicString(permission)
    }

    fun onDestroy() {
        mSvp.setVideoAllCallBack(null)
        mHandler.removeCallbacksAndMessages(null)
        GSYVideoManager.releaseAllVideos()
    }

    fun getExitInfo(): String {
        return mLocalMusicModel.getExitString()
    }

    fun getFilterFailInfo(): String {
        return mLocalMusicModel.getFilterFailString()
    }

    fun seekTo(currentProgress: Int) {
        mSvp.seekTo(currentProgress.toLong())
    }

    fun isPlaying(): Boolean {
        return mSvp.currentState == CURRENT_STATE_PLAYING
    }

    fun play(){
        mSvp.onVideoResume()
    }

    fun pause(){
        mSvp.onVideoPause()
    }

    fun setVideoPlayer(svp: StandardGSYVideoPlayer) {
        mSvp = svp
        mSvp.setVideoAllCallBack(this)
        PlayerFactory.setPlayManager(Exo2PlayerManager::class.java)
    }

    override fun onStartPrepared(url: String?, vararg objects: Any?) {

    }

    override fun onPrepared(url: String, vararg objects: Any) {
        try {
            play()
            mLocalMusicActivity.onProgress(0, mSvp.duration.toInt())
            mLocalMusicActivity.onMediaPlayerPrepared()
            sendProgress()
            try {
                CoroutineScope(Dispatchers.IO).launch {
                    mMmr.setDataSource(mCurrentLocalMusicPath)
                    val bytes = mMmr.embeddedPicture
                    if (bytes != null) {
                        val bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
                        withContext(Dispatchers.Main) {
                            mLocalMusicActivity.refreshAlbumImg(bitmap)
                        }
                    }
                }
            } catch (e: Exception) {
                Log.d(TAG, "缓冲专辑封面失败")
            }
        } catch (e: Exception) {
            CoroutineScope(Dispatchers.Main).launch {
                mLocalMusicActivity.onError()
                mLocalMusicActivity.showToast(mLocalMusicModel.getPrepareErrorString())
            }
            e.printStackTrace()
            Log.d(TAG, "缓冲失败2")
        }
    }

    override fun onClickStartIcon(url: String?, vararg objects: Any?) {

    }

    override fun onClickStartError(url: String?, vararg objects: Any?) {

    }

    override fun onClickStop(url: String?, vararg objects: Any?) {

    }

    override fun onClickStopFullscreen(url: String?, vararg objects: Any?) {

    }

    override fun onClickResume(url: String?, vararg objects: Any?) {

    }

    override fun onClickResumeFullscreen(url: String?, vararg objects: Any?) {

    }

    override fun onClickSeekbar(url: String?, vararg objects: Any?) {

    }

    override fun onClickSeekbarFullscreen(url: String?, vararg objects: Any?) {

    }

    override fun onAutoComplete(url: String?, vararg objects: Any?) {
        mLocalMusicActivity.autoChangeNextSong()
    }

    override fun onComplete(url: String, vararg objects: Any) {

    }

    override fun onEnterFullscreen(url: String?, vararg objects: Any?) {

    }

    override fun onQuitFullscreen(url: String?, vararg objects: Any?) {

    }

    override fun onQuitSmallWidget(url: String?, vararg objects: Any?) {

    }

    override fun onEnterSmallWidget(url: String?, vararg objects: Any?) {

    }

    override fun onTouchScreenSeekVolume(url: String?, vararg objects: Any?) {

    }

    override fun onTouchScreenSeekPosition(url: String?, vararg objects: Any?) {

    }

    override fun onTouchScreenSeekLight(url: String?, vararg objects: Any?) {

    }

    override fun onPlayError(url: String?, vararg objects: Any?) {

    }

    override fun onClickStartThumb(url: String?, vararg objects: Any?) {

    }

    override fun onClickBlank(url: String?, vararg objects: Any?) {

    }

    override fun onClickBlankFullscreen(url: String?, vararg objects: Any?) {

    }
}